<?php


namespace app\api\controller\Order;


use app\api\controller\AppController;
use app\api\controller\WeiXinPayUtil;
use app\api\model\Collage\CollageModel;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\User\MerchantWalletModel;
use app\api\model\User\UserWalletModel;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use app\Utils\WechatPayUtil;
use Exception;
use think\facade\Db;

class Order extends AppController
{

    /**
     * @api {get} /get_order_list 订单列表
     * @apiGroup 订单信息
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiParam {int} type 订单类型 1:商品;2:会员;3:课程 （-2全部）
     * @apiParam {int} is_group 0：普通订单 1：团购订单 （-2全部）
     * @apiParam {int} status 订单状态 0：未支付；1：待发货；2：待收货；3：完成；4：取消 -1: 已失效 （-2全部） 10：拼团中
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getOrderList(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        $type = !empty($param['type']) ? $param['type'] : 1;
        $status = !empty($param['status']) ? $param['status'] : 0;
        $is_group = !empty($param['is_group']) ? $param['is_group'] : 0;
        $where = [
            ['uid', '=', $user['id']]
        ];
        if (!empty($type)) {
            array_push($where, ['type', '=', $type]);
        }
        if (isset($status)) {
            if ($status != -2) {
                array_push($where, ['status', '=', $status]);
            }
        }
        if (isset($is_group)) {
            if ($is_group != -2) {
                array_push($where, ['is_group', '=', $is_group]);
            }
        }
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;

        $list = OrderModel::getOrderListWherePage($page, $limit, $where);
        foreach ($list as &$item) {
            foreach ($item['list'] as &$val) {
                $goods_info = json_decode($val['goods_info'], true);
                $goods_info['img'] = ImageUtil::i()->replaceUrl($goods_info['img']);
                $goods_info['label'] = !empty($goods_info['label']) ? json_decode($goods_info['label'], true) : [];
                $val['goods_info'] = $goods_info;
            }
            if (!empty($item['is_group']) && !empty($item['collage_id'])) {
                //拼团信息
                $collage = CollageModel::getCollageWhere([['id', '=', $item['collage_id']]]);
                if (!empty($collage)) {
                    if (empty($collage['status'])) {
                        $item['status'] = 10;
                    }
                }
                $users = OrderModel::getOrderListWhereMore([['o.collage_id', '=', $item['collage_id']]], 'u.head_img,u.nickname');
                foreach ($users as &$user) {
                    $user['head_img'] = ImageUtil::i()->replaceUrl($user['head_img']);
                }
                unset($user);
                $item['users'] = $users;
            } else {
                $item['users'] = [];
            }
        }

        $count = OrderModel::getOrderListWhereCount($where);
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

    /**
     * @api {get} /get_order_info 订单详情
     * @apiGroup 订单信息
     * @apiParam {int} id 订单ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getOrderInfo(Request $request)
    {
        $param = $request->param();
        $id = !empty($param['id']) ? $param['id'] : 0;
        $order = OrderModel::getOrderWhere([['id', '=', $id]]);
        return Util::returnJson(self::CODE_SUCCESS, $order);
    }

    /**
     * @api {post} /get_order_pay 去支付
     * @apiGroup 订单信息
     * @apiParam {int} id 订单ID
     * @apiParam {int} source_type 来源 1:APP 2:微信公众号 3:小程序
     * @apiParam {int} pay_way 支付方式 1:余额 2:支付吧 3:微信
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getOrderPay(Request $request)
    {
        $param = $request->param();
        $id = !empty($param['id']) ? $param['id'] : 0;
        //1:APP 2:微信公众号 3:小程序
        if (!in_array($param['source_type'], [1, 2, 3])) {
            return Util::returnJson(self::CODE_ERROR, null, "来源错误");
        }
        if (!in_array($param['pay_way'], [1, 2, 3])) {
            return Util::returnJson(self::CODE_ERROR, null, "支付类型错误");
        }
        if (empty($id)) {
            return Util::returnJson(self::CODE_ERROR, null, "参数错误");
        }
        if (!empty($type)) {
            return Util::returnJson(self::CODE_ERROR, null, "请选择支付方式");
        }
        //商户订单号
        $out_trade_no = StrUtil::i()->getOrderSn(3);

        $order = OrderModel::getOrderWhere(['id' => $id]);
        if (empty($order)) {
            return Util::returnJson(self::CODE_ERROR, null, "订单不存在");
        }
//        if (!empty($order['status'])) {
//            return Util::returnJson(self::CODE_ERROR, null, "订单已处理");
//        }
        $result = null;
        $result1 = null;
        if ($param['pay_way'] == 1) {
            //余额支付
        } else if ($param['pay_way'] == 2) {
            $order_save = [
                'pay_way' => $param['pay_way'],
                'out_trade_no' => $out_trade_no
            ];
            OrderModel::updateOrderWhere([['id', '=', $order['id']]], $order_save);
            //支付宝支付
            $result = $this->aliPay($order['total_price'], $out_trade_no, "商品支付");

        } else if ($param['pay_way'] == 3) {
            //微信支付
            $order_save = [
                'out_trade_no' => $out_trade_no
            ];
            OrderModel::updateOrderWhere([['id', '=', $order['id']]], $order_save);
            $wx = new WechatPayUtil();

            $result1 = $wx->wechat_pay($out_trade_no, $order['total_price'], '购买商品支付');
        }
        if ($result['code'] == 0) {
            $data = [
                'pay_way' => $param['pay_way'],
                'pay_info' => $result?$result['data']:'',
                'wx_pay' => $result1
            ];
            return Util::returnJson(self::CODE_SUCCESS, $data, "获取支付参数成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, $result['msg']);
        }
    }

    /**
     * @api {post} /cancel_order 取消订单
     * @apiGroup 订单信息
     * @apiParam {int} id 订单ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function cancelOrder(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $id = !empty($param['id']) ? $param['id'] : 0;
        if (empty($id)) {
            return Util::returnJson(self::CODE_ERROR, null, "参数错误");
        }
        $order = OrderModel::getOrderWhere(['id' => $id]);
        if (empty($order)) {
            return Util::returnJson(self::CODE_ERROR, null, "订单不存在");
        }
        if ($order['status'] >= 1) {
            if ((time() - strtotime($order['up_time'])) > 1800) {
                return Util::returnJson(self::CODE_ERROR, null, "订单付款大于30分钟无法取消！");
            }
        }

        Db::startTrans();
        try {
            if (!empty($order['status']) && $order['status'] != -1) {
                //订单退款
                if ($order['pay_way'] == 1) {
                    //余额
                }
                if ($order['pay_way'] == 2) {
                    //支付宝
                    $result = $this->aliRefund($order['total_price'], $order['out_trade_no']);
                }
                if ($order['pay_way'] == 3) {
                    //微信
                    $wx = new WechatPayUtil();
                    $result = $wx->refund($order['total_price'], $order['out_trade_no']);
                }
                if ($result['code'] == 0) {
                    $save = [
                        'status' => 4,
                        'up_time' => date("Y-m-d H:i:s", time())
                    ];
                    OrderModel::updateOrderWhere([['id', '=', $order['id']]], $save);
                    $order_goods = OrderGoodsModel::getOrderGoodsListWhereMore([['order_id', '=', $order['id']]]);
                    foreach ($order_goods as $item) {
                        $goods_save = [
                            'status' => 4,
                            'up_time' => date("Y-m-d H:i:s", time())
                        ];
                        OrderGoodsModel::updateOrderGoodsWhere([['id', '=', $item['id']]], $goods_save);
                    }
                    return Util::returnJson(self::CODE_SUCCESS, null, "取消订单成功！");
                } else {
                    return Util::returnJson(self::CODE_ERROR, null, $result['msg']);
                }
            } else {
                //直接取消
                $save = [
                    'status' => 4,
                    'up_time' => date("Y-m-d H:i:s", time())
                ];
                $flag = OrderModel::updateOrderWhere([['id', '=', $order['id']]], $save);
                if ($flag) {
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS, null, "取消成功！");
                } else {
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR, null, "取消失败！");
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR, null, "取消失败！");
        }

    }

    /**
     * @api {post} /del_order 删除订单
     * @apiGroup 订单信息
     * @apiParam {int} id 订单ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function delOrder(Request $request)
    {
        $param = $request->param();
        $id = !empty($param['id']) ? $param['id'] : 0;
        $flag = OrderModel::deleteOrderWhere([['id', '=', $id]]);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "删除成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, '删除失败');
        }
    }

    /**
     * @api {post} /confirm_receipt_order 确认收货
     * @apiGroup 订单信息
     * @apiParam {int} id 订单ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function confirmReceiptOrder(Request $request)
    {
        $param = $request->param();
        $id = !empty($param['id']) ? $param['id'] : 0;
        if (empty($id)) {
            return Util::returnJson(self::CODE_ERROR, null, "参数错误");
        }
        $order = OrderModel::getOrderWhere(['id' => $id]);
        if (empty($order)) {
            return Util::returnJson(self::CODE_ERROR, null, "订单不存在");
        }
        if ($order['status'] != 2) {
            if ((time() - strtotime($order['up_time'])) > 1800) {
                return Util::returnJson(self::CODE_ERROR, null, "订单状态错误！");
            }
        }
        Db::startTrans();
        try {
            $save = [
                'status' => 3,
                'up_time' => date("Y-m-d H:i:s", time())
            ];
            $flag = OrderModel::updateOrderWhere([['id', '=', $order['id']]], $save);
            if ($flag) {
                $save_goods = [
                    'status' => 3,
                    'up_time' => date("Y-m-d H:i:s", time())
                ];
                $flag = OrderGoodsModel::updateOrderGoodsWhere([['order_id', '=', $order['id']]], $save_goods);
                if ($flag) {
                    $goods = OrderGoodsModel::getOrderGoodsListWhereMore([['order_id', '=', $order['id']]]);
                    if ($order['type'] == 1) {
                        foreach ($goods as $item) {
                            ## 平台抽成
                            if ($item['mer_id']) {
                                $item['ratio'] = $item['ratio'] > 1 ? 1 : $item['ratio'];
                                #增加商家钱包余额
                                $result = MerchantWalletModel::walletIn($item['mer_id'], round($item['total_price'] * (1 - $item['ratio']), 2), StrUtil::MER_BILL_USE_TYPE['SELL_GOODS'], '售卖商品');
                                if (false === $result) {
                                    Db::rollback();
                                    return Util::returnJson(self::CODE_ERROR, null, "确认收货失败！");
                                }
                            }
                            ## 发放佣金
                            if ($item['is_sales'] == 1 || $item['is_sales'] == 2) {
                                if (!empty($item['agnet_uid1']) && $item['agent_amount1'] > 0 && $item['agent_status1'] == 0) {
                                    UserWalletModel::walletIn($item['agnet_uid1'], $item['agent_amount1'], StrUtil::BILL_USE_TYPE['GOODS_COMMISSION'], "商品佣金", $item['id']);
                                    OrderGoodsModel::updateOrderGoodsWhere(['id' => $item['id']], ['agent_status1' => 1]);
                                    Db::name('user_wallet')->where('uid', $item['agnet_uid1'])->inc('reward', $item['agent_amount1'])->update();
                                }
                                if (!empty($item['agnet_uid2']) && $item['agent_amount2'] > 0 && $item['agent_status2'] == 0) {
                                    UserWalletModel::walletIn($item['agnet_uid2'], $item['agent_amount2'], StrUtil::BILL_USE_TYPE['GOODS_COMMISSION'], "商品佣金", $item['id']);
                                    OrderGoodsModel::updateOrderGoodsWhere(['id' => $item['id']], ['agent_status2' => 1]);
                                    Db::name('user_wallet')->where('uid', $item['agnet_uid2'])->inc('reward', $item['agent_amount2'])->update();
                                }
                                if (!empty($item['agnet_uid3']) && $item['agent_amount3'] > 0 && $item['agent_status3'] == 0) {
                                    UserWalletModel::walletIn($item['agnet_uid3'], $item['agent_amount3'], StrUtil::BILL_USE_TYPE['GOODS_COMMISSION'], "商品佣金", $item['id']);
                                    OrderGoodsModel::updateOrderGoodsWhere(['id' => $item['id']], ['agent_status3' => 1]);
                                    Db::name('user_wallet')->where('uid', $item['agnet_uid3'])->inc('reward', $item['agent_amount3'])->update();
                                }
                            }
                        }
                    }
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS, null, "确认收货成功！");
                } else {
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR, null, "确认收货失败！");
                }
            } else {
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR, null, "确认收货失败！");
            }
        } catch (Exception $e) {
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR, null, "确认收货失败！");
        }
    }

}